package com.ym.medical.service.impl;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ym.base.domain.MobileSearchParam;
import com.ym.common.utils.StringUtil;
import com.ym.core.exception.BusinessException;
import com.ym.core.redis.RedisKeyEnum;
import com.ym.core.redis.RedisUtil;
import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.core.utils.tkmybatis.TK;
import com.ym.medical.dao.HospitalDao;
import com.ym.medical.domain.entity.DataMainPicEntity;
import com.ym.medical.domain.entity.HospitalEntity;
import com.ym.medical.domain.param.DataMainPicpParam;
import com.ym.medical.domain.param.HosSosQryParam;
import com.ym.medical.domain.param.HospitalParam;
import com.ym.medical.domain.param.HospitalQueryParam;
import com.ym.medical.domain.param.HospitalRankEditParam;
import com.ym.medical.domain.param.HospitalUpdateParam;
import com.ym.medical.domain.vo.HosSosVo;
import com.ym.medical.domain.vo.HospitalDetailVo;
import com.ym.medical.domain.vo.HospitalListPcVO;
import com.ym.medical.domain.vo.HospitalListVO;
import com.ym.medical.domain.vo.HospitalVo;
import com.ym.medical.enums.CodeRuleEnum;
import com.ym.medical.service.IDataMainPicSV;
import com.ym.medical.service.IHospitalSV;
import com.ym.medical.service.IStandardDeptSV;
import com.ym.medical.service.ISysCodeRuleSV;
import com.ym.soso.domain.entity.RegistryWayEntity;
import com.ym.soso.domain.param.RegistryWayParam;
import com.ym.soso.enums.PublishStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
* 【请填写功能名称】Service业务层处理
*
* @author ym
* @date 2020-08-19
*/
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class HospitalSVImpl extends BaseSVImpl<HospitalEntity,HospitalDao> implements IHospitalSV {

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private IStandardDeptSV iStandardDeptSV;


	@Autowired
	private ISysCodeRuleSV iSysCodeRuleSV;

    //@Autowired
    //private IRegistryWaySV iRegistryWaySV;


    @Autowired
    private IDataMainPicSV iDataMainPicSV;

	//@Autowired
	//private HospitalSearchIdxService hospitalSearchIdxService;

	/**
	 * 查询【请填写功能名称】列表
	 *
	 * @param queryParam 【请填写功能名称】 查询参数
	 * @return 【请填写功能名称】
	 */
	@Override
	public List<HospitalListPcVO> selectListPC(HospitalQueryParam queryParam) {
		List<HospitalListPcVO> hospitals = mapper.selectListPC(queryParam);
		return hospitals;
	}

	/**
	 * 新增【请填写功能名称】
	 *
	 * @param updateParam 【请填写功能名称】 新增参数
	 * @return 结果
	 */
	@Override
	public Long insertPC(HospitalUpdateParam updateParam) {
            HospitalEntity entity = updateParam.covert();
		this.insert(entity);

		//hospitalSearchIdxService.saveOrUpdate(entity);
		return entity.getId();
	}

	/**
	 * 修改【请填写功能名称】
	 *
	 * @param updateParam 【请填写功能名称】 修改参数
	 * @return 结果
	 */
	@Override
	public int updateByIdPC(HospitalUpdateParam updateParam) {
            HospitalEntity entity = updateParam.covert("createTime");
		int result = this.updateById(entity);
		//hospitalSearchIdxService.saveOrUpdate(entity);
		return result;
	}

	/**
	 * 手机端医院
	 * @param queryParam
	 * @return
	 */
	@Override
	public List<HospitalListVO> selectHospitals(HospitalQueryParam queryParam) {
		// 关键词过滤
		MobileSearchParam args = MobileSearchParam.build(queryParam.getProv(), queryParam.getCity(), queryParam.getArea(), queryParam.getKeyword());
		//List<Long> ids = hospitalSearchIdxService.searchByKeywordOfIds(args);
		//if (StringUtil.isNotBlank(args.getKeyword()) && ids.isEmpty()) {
		//	return Collections.emptyList();
		//}
		//if(!ids.isEmpty()){
		//	queryParam.setIds(ids);
		//}
		if(StringUtil.isNotBlank(args.getKeyword())){
			queryParam.setKeywordSort(true);
		}
		return mapper.selectHospitals(queryParam);
	}

	/**
	 * 医院详情
	 * @param id
	 * @param currId
	 * @return
	 */
	@Override
	public HospitalDetailVo resultMap(Long id, Long currId) {
		HospitalDetailVo hospitalDetailVo = mapper.resultMap(id, currId);
		//点击量加一(放入缓存)
		long lon = redisUtil.incr(RedisKeyEnum.HOSPITAL_CLICK_ON_INC.build(String.valueOf(id)), 1);
		String hashKey = RedisKeyEnum.HOSPITAL_CLICK_ON_INC.build("increase");
		//重置数值
		boolean bool = redisUtil.hset(hashKey, String.valueOf(id), String.valueOf(lon));
		if (!bool) {
			log.info("医院点击量存储异常:医院id:{}", id);
		}
		return hospitalDetailVo;
	}

	/**
	 * 急救医院列表
	 *
	 * @param sosQryParam
	 * @return
	 */
	@Override
	public List<HosSosVo> hosSos(HosSosQryParam sosQryParam) {
		List<HosSosVo> hosSosVos = mapper.hosSos(sosQryParam);
		return hosSosVos;
	}

	/**
	 * pc 医院添加
	 * @param hospital
	 * @param wayParams
	 * @param picIds
	 * @return
	 */
	@Override
	public long addH(HospitalEntity hospital, List<RegistryWayParam> wayParams, List<DataMainPicpParam> picIds) {
		long rows = 0;
		String theCode = hospital.getHosCode();
		if (null == theCode || "".equals(theCode)) {
			theCode = iSysCodeRuleSV.createCode(CodeRuleEnum.HOSPITAL);
			hospital.setHosCode(theCode);
		}
		mapper.insertSelective(hospital);
		Long hosId = hospital.getId();

		if (wayParams != null && !wayParams.isEmpty()) {
			for (RegistryWayParam param : wayParams) {
                RegistryWayEntity convert = param.covert();
				convert.setRelationId(hosId);
				convert.setTheType("01");
				convert.setCreSb(hospital.getCreated());
               // rows = iRegistryWaySV.insert(convert);
			}

		}

		if (picIds != null && !picIds.isEmpty()) {
			DataMainPicEntity dataMainPic = null;
			for (DataMainPicpParam pic : picIds) {
				dataMainPic = new DataMainPicEntity();
				dataMainPic.setPicId(pic.getPicId());
				dataMainPic.setRelId(hosId);
				dataMainPic.setFlag("01");
				dataMainPic.setPublishStatus(PublishStatusEnum.HAS_BEEN_RELEASED.getKey());
				dataMainPic.setCreSb(hospital.getCreated());
                rows = iDataMainPicSV.insert(dataMainPic);
			}

		}
		//hospitalSearchIdxService.saveOrUpdate(hospital);
		return rows;

	}
	/**
	 * 医院修改
	 *
	 * @param hospital
	 * @param pics
	 * @param wayList
	 * @return
	 */
	@Override
	public long updateOrInsert(HospitalEntity hospital, List<RegistryWayParam> wayList, List<DataMainPicpParam> pics) {
		long rows = 0;
		rows = mapper.updateByPrimaryKeySelective(hospital);
		Long hosId = hospital.getId();
		if (wayList != null && !wayList.isEmpty()) {
			for (RegistryWayParam registryWay : wayList) {
				registryWay.setRelationId(hosId);
				registryWay.setTheType("01");
				if (registryWay.getId() == null) {
					RegistryWayEntity registryWay1 = registryWay.covert();
					registryWay1.setCreSb(hospital.getUpdated());
					//rows = iRegistryWaySV.insert(registryWay1);
				} else {
					RegistryWayEntity registryWay1 = registryWay.covert();
					registryWay1.setUptSb(hospital.getUpdated());
					registryWay1.setRelationId(hosId);
					registryWay1.setTheType("01");
					//rows = iRegistryWaySV.updateById(registryWay1);
				}
			}
		}
		if (pics != null && !pics.isEmpty()) {
			for (DataMainPicpParam pic : pics) {
				//不为空 下线
				if (pic.getId() != null && pic.getDeleted()) {
					DataMainPicEntity pic1 = pic.covert();
					pic1.setPublishStatus(PublishStatusEnum.UN_PUBLISHED.getKey());
					iDataMainPicSV.updateById(pic1);
					//新增
				} else if (pic.getId() == null) {
					DataMainPicEntity pic1 = pic.covert();
					pic1.setRelId(hosId);
					pic1.setPublishStatus(PublishStatusEnum.HAS_BEEN_RELEASED.getKey());
					pic1.setFlag("01");
					pic1.setCreSb(hospital.getUpdated());
					iDataMainPicSV.insert(pic1);
				}

			}
		}
		//hospitalSearchIdxService.saveOrUpdate(hospital);
		return rows;
	}

	/**
	 * soso pc 医院列表
	 *
	 * @param pageNo
	 * @param limit
	 * @param hospitalQryParam
	 * @return
	 */
	@Override
	public PageInfo<HospitalVo> hospitalList(int pageNo, int limit, HospitalQueryParam hospitalQryParam) {
		PageHelper.startPage(pageNo, limit);
		List<HospitalVo> pageHospital = mapper.hospitalList(hospitalQryParam);
		return new PageInfo<>(pageHospital);
	}

	/**
	 * pc 医院详情
	 *
	 * @param id
	 * @return
	 */
	@Override
	public HospitalDetailVo pcResultMap(Long id) {
		HospitalDetailVo hospitalDetailVo = mapper.resultPcMap(id, null);
		return hospitalDetailVo;
	}

	/**
	 * 医院排名列表
	 *
	 * @param pageNo
	 * @param limit
	 * @param hospitalQryParam
	 * @return
	 */
	@Override
	public PageInfo<HospitalVo> hospitalRankList(int pageNo, int limit, HospitalQueryParam hospitalQryParam) {
		PageHelper.startPage(pageNo, limit);
		List<HospitalVo> hospitalVos = mapper.hospitalRankList(hospitalQryParam);
		return new PageInfo<>(hospitalVos);
	}

	/**
	 * 医院排名修改
	 *
	 * @param hospitalEditParam
	 * @return
	 */
	@Override
	public int updateByMyId(HospitalRankEditParam hospitalEditParam) {
		return mapper.updateByMyId(hospitalEditParam);
	}

	/**
	 * 查询医院列表
	 *
	 * @param pageNo        页码
	 * @param limit         每页规格
	 * @param hospitalModel 实体对象
	 * @return
	 */
	@Override
	public PageInfo<HospitalEntity> getHospitalList(int pageNo, int limit, HospitalParam hospitalModel) {
		PageHelper.startPage(pageNo, limit);
		return new PageInfo<HospitalEntity>(mapper.getHospitalList(hospitalModel));
	}

	/**
	 * 导入医院信息
	 *
	 * @param hospitalList
	 * @return
	 */
	@Override
	public Map<String, Object> uploadIntoHospital(List<HospitalEntity> hospitalList) {
		List<HospitalEntity> hospitals = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		int rows = 0;

		for (HospitalEntity hospital : hospitalList) {
			if (null == hospital.getHosName() || "".equals(hospital.getHosName())) {
				continue;
			}
			hospital.setState("01");
			hospital.setCreateTime(new Date());
			hospital.setUpdateTime(new Date());
			//hospitals.add(hospital);
			try {
				mapper.insertSelective(hospital);
				rows++;
			} catch (Exception e) {
				log.error(ExceptionUtil.getMessage(e));
				if (e instanceof DuplicateKeyException) {
					hospitals.add(hospital);
					//System.out.println(hospitals);

				}
			}
			continue;
		}
		map.put("successCount", rows);
		map.put("repeatDetail", hospitals);

		return map;
	}
	/**
	 * 医院所有信息
	 *
	 * @return
	 */
	@Override
	public PageInfo<HospitalEntity> getAllhospitalList(int pageNo, int limit, HospitalParam model) {
		PageHelper.startPage(pageNo, limit);
		List<HospitalEntity> hospitalList = mapper.getAllhospitalList(model);
		if (hospitalList.isEmpty()) {
			throw new BusinessException("没有您要的数据");
		}
		return new PageInfo<>(hospitalList);
	}

	/**
	 * 添加医院
	 *
	 * @param hospital
	 * @return
	 */
	@Override
	public int addHospital(HospitalEntity hospital) {
		if (null == hospital) {
			throw new BusinessException("保存对象不能为空");
		}
		if (StringUtils.isEmpty(hospital.getHosName())) {
			throw new BusinessException("医院名不能为空");
		}
		if (StringUtils.isEmpty(hospital.getHosLevel())) {
			throw new BusinessException("医院等级不能为空");
		}
		if (StringUtils.isEmpty(hospital.getAddrDesc())) {
			throw new BusinessException("医院地址不能为空");
		}

		hospital.setCreateTime(new Date());
		hospital.setUpdateTime(new Date());
		hospital.setState("01");//正常
		int rows = mapper.insertSelective(hospital);
		return rows;
	}

	/**
	 * 医院信息更改
	 *
	 * @param hospital
	 * @return
	 */
	@Override
	public int updateHospital(HospitalEntity hospital) {
		hospital.setUpdateTime(new Date());
		int rows = mapper.updateByPrimaryKeySelective(hospital);
		return rows;
	}

	/**
	 * 医院code校验
	 *
	 * @param hosCode
	 */
	@Override
	public void repeatHosCode(String hosCode) {
		HospitalEntity hospital = mapper.selectOneByExample(
				TK.select(HospitalEntity.class).column("id","hos_code")
				.where().andEqualTo(HospitalEntity::getHosCode,hosCode).end());

		if (hospital != null) {
			throw new BusinessException("医院编码重复");
		}
	}

	/**
	 * 医院下拉搜索
	 *
	 * @param hosName
	 * @return
	 */
	@Override
	public List<HospitalEntity> dropdownSearch(String hosName) {
		List<HospitalEntity> hosNames = mapper.selectHosName(hosName);
		return hosNames;
	}


	/**
	 * 所有医院名
	 *
	 * @return
	 */
	@Override
	public List<HospitalEntity> selectHosName() {
		String hosName = "";
		List<HospitalEntity> hospitals = mapper.selectHosName(hosName);
		return hospitals;
	}

}
